package com.eastfair.certificate.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.eastfair.boot.request.PageParams;
import com.eastfair.boot.service.SuperCacheServiceImpl;
import com.eastfair.cache.certificate.CertificatePeopleCacheKeyBuilder;
import com.eastfair.certificate.dao.PeopleMapper;
import com.eastfair.certificate.entity.CertificateIndex;
import com.eastfair.certificate.entity.CertificateUser;
import com.eastfair.certificate.entity.People;
import com.eastfair.certificate.service.PeopleService;
import com.eastfair.boot.service.SuperServiceImpl;
import com.eastfair.core.context.ContextUtil;
import com.eastfair.core.model.CacheKeyBuilder;
import com.eastfair.core.utils.ConvertUtil;
import com.eastfair.database.mybatis.conditions.Wraps;
import com.eastfair.database.mybatis.conditions.query.QueryWrap;
import com.eastfair.database.mybatis.typehandler.TypeHandlerUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.eastfair.constant.BusinessConstant;
import com.eastfair.core.base.R;

import java.util.Collection;

//import com.baomidou.dynamic.datasource.annotation.DS;
import org.springframework.aop.framework.AopContext;
import com.eastfair.annotation.annotation.cache.Magic;
import com.eastfair.annotation.annotation.cache.Cache;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.commons.lang3.StringUtils;
//import com.baomidou.dynamic.datasource.annotation.DS;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.List;

import com.eastfair.certificate.vo.*;
import com.eastfair.certificate.dto.*;

/**
 * <p>
 * 业务实现类
 * 人员库
 * </p>
 *
 * @author ligang
 * @date 2023-03-07
 */
@Slf4j
@Service
//@DS("#thread.tenant")
public class PeopleServiceImpl extends SuperCacheServiceImpl<PeopleMapper, People> implements PeopleService {


    /**
     * 处理新增相关处理
     *
     * @param model 实体
     * @return 是否成功
     */
    @Override
    public R<Boolean> handlerSave(People model) {
        model.setProjectId(ContextUtil.getProjectId());
        model.setSubsystemId(ContextUtil.getSubSystemId());
        model.setTeamId(ContextUtil.getTeamId());
        model.setIsDeleted(BusinessConstant.NO);
        model.setIsEnabled(BusinessConstant.YES);
        //雪花ID
        return R.successDef();
    }


    /**
     * 处理逻辑删除相关处理
     *
     * @param modelList 实体
     * @return 是否成功
     */
    @Override
    protected R<Boolean> handlerRemoveByIdsOfLogic(Collection<People> modelList) {
        modelList.stream().forEach(s -> {
            s.setIsDeleted(BusinessConstant.YES);
        });
        // TODO: 2021/10/29 这里需要操作其他业务，如清空角色等
        return R.successDef();
    }

    /**
     * 通用查询
     *
     * @param modelDTO DTO
     * @param ids      主键id集合
     * @return list
     */
    @Override
    public List<People> list(PeopleDTO modelDTO, List<Long> ids) {
        return ((PeopleService) AopContext.currentProxy()).listOfCache(modelDTO, ids);
    }


    /**
     * 缓存查询
     *
     * @param modelDTO DTO
     * @param ids      主键id集合
     * @return list
     */
    @Override
    @Cache(key = "",
            magic = @Magic(
                    key = "{" +
                            "{'cardFront', #args[0]?.cardFront}," +
                            "{'cardBack', #args[0]?.cardBack}," +
                            "{'cardNumber', #args[0]?.cardNumber}," +
                            "{'fullName', #args[0]?.fullName}," +
                            "{'gender', #args[0]?.gender}," +
                            "{'contactInformation', #args[0]?.contactInformation}," +
                            "{'workCertificateImg', #args[0]?.workCertificateImg}," +
                            "{'teamId', #args[0]?.teamId}," +
                            "{'isEnabled', #args[0]?.isEnabled}," +
                            "{'id', #args[1]}" +
                            "}"))
    public List<People> listOfCache(PeopleDTO modelDTO, List<Long> ids) {
        //查询
        People queryModel = new People();
        if (modelDTO != null) {
            BeanUtils.copyProperties(modelDTO, queryModel);
        }
        QueryWrap<People> wrapper = Wraps.q(queryModel);
        if (ids != null && !ids.isEmpty()) {
            wrapper.lambda().in(People::getId, ids);
        }
        //添加其他业务查询条件
        wrapper.lambda().eq(People::getIsDeleted, BusinessConstant.DELETE_NO);
        List<People> modelList = list(wrapper);
        return modelList;
    }

    @Override
    public void executePeople(PeopleDTO peopleDTO) {
        if(StringUtils.isNotBlank(peopleDTO.getCardNumber())){
            PeopleDTO peopleDTO2 = new PeopleDTO();
            peopleDTO2.setCardNumber(peopleDTO.getCardNumber());
            List<People> peopleList = list(peopleDTO2, null);
            if (CollectionUtil.isNotEmpty(peopleList)) {
                //更新
                for (People people : peopleList) {
                    peopleDTO.setId(people.getId());
                    BeanUtils.copyProperties(peopleDTO, people);
                    updateById(people);
                }
            } else {
                //新增
                People people = new People();
                BeanUtils.copyProperties(peopleDTO, people);
                save(people);
            }
        }
    }


    /**
     * do转vo
     *
     * @param model model
     * @return modelVo
     */
    @Override
    public PeopleVO doToVo(People model) {
        PeopleVO modelVo = new PeopleVO();
        BeanUtils.copyProperties(model, modelVo);
        modelVo.setId(model.getId());
        return modelVo;
    }

    /**
     * do转vo
     *
     * @param modelList modelList
     * @return list
     */
    @Override
    public List<PeopleVO> doToVos(List<People> modelList) {
        if (modelList == null || modelList.isEmpty()) {
            return null;
        }
        List<PeopleVO> result = new ArrayList<>();
        for (People model : modelList) {
            result.add(doToVo(model));
        }
        return result;
    }

    @Override
    public CacheKeyBuilder getCacheKeyBuilder() {
        return new CertificatePeopleCacheKeyBuilder();
    }


    @Override
    public IPage<People> pageVo(PageParams<People> params) {
        IPage<People> page = params.buildPage();
        People people = params.getModel();
        //查询加密处理
//        assbmlePrivateKey(people);

        QueryWrap<People> queryWrapper = Wraps.q(people);
        queryWrapper.lambda().select(
                People::getCompanyId,
                People::getCardFront, People::getCardBack, People::getPrincipalType,
                People::getCardNumber, People::getFullName, People::getGender, People::getContactInformation,
                People::getWorkType, People::getWorkCertificateImg);

        queryWrapper.lambda().groupBy(
                People::getCompanyId,
                People::getCardFront, People::getCardBack, People::getPrincipalType,
                People::getCardNumber, People::getFullName, People::getGender, People::getContactInformation,
                People::getWorkType, People::getWorkCertificateImg);

        //page entity转vo
        IPage<People> peopleIPage = page(page, queryWrapper);
        return peopleIPage;
    }

    //查询加密处理
    public void assbmlePrivateKey(People people){
        if(StringUtils.isNotBlank(people.getContactInformation())){
            people.setContactInformation(TypeHandlerUtil.crypt(people.getContactInformation()));
        }
        if(StringUtils.isNotBlank(people.getCardNumber())){
            people.setCardNumber(TypeHandlerUtil.crypt(people.getCardNumber()));
        }
    }


}
